package com.twj.tools.poi;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.twj.tools.parse.CastUtils;
import com.twj.tools.parse.JsonUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.twj.tools.img.ImageUtil.convertBase64StrToImage;


/**
 * @author 作者: tianwenju
 * @version 1.0
 * @project 金税三期工程核心征管及应用总集成项目
 * @package com.css.dsjypt
 * @file WordPdfTest.java 创建时间:2023年06月26日 16:46
 * @title 标题（要求能简洁地表达出类的功能和职责）
 * @description 描述（简要描述类的职责、实现方式、使用注意事项等）
 * @copyright Copyright (c) 2020 中国软件与技术服务股份有限公司
 * @company 中国软件与技术服务股份有限公司
 * @module 模块: 模块名称
 * @reviewer 审核人:
 * @history 修订历史（历次修订内容、修订人、修订时间等）
 */
public class PdfUtil {


    /**
     * 居左
     */
    private final static int ALIGN_LEFT = 0;
    /**
     * 居中
     */
    private final static int ALIGN_CENTER = 1;
    /**
     * 居右
     */
    private final static int ALIGN_RIGHT = 2;

    /**
     * 图片宽度尺寸
     */
    private final static int IMG_WIDTH_SIZE = 400;
    //定义全局的字体静态变量
    private static Font titlefont;
    private static Font headfont;
    private static Font headbody;
    private static Font keyfont;
    private static Font textfont;
    private static Font imageFont;

    // 静态代码块
    static {
        try {
            // 不同字体（这里定义为同一种字体：包含不同字号、不同style）   只需要将itextpdf版本改为5.5.5; itext-asian版本改为5.2.0即可
//            final HttpServletRequest request = ContextAPI.getReq();
//            final String msgothic = request.getSession().getServletContext().getRealPath("/yqssdsj/download/font" + File.separator + "msgothic.ttc");
//            final String SIMYOU = request.getSession().getServletContext().getRealPath("/yqssdsj/download/font" + File.separator + "SIMYOU.TTF");

            BaseFont bfChinese = BaseFont.createFont("D:/test/SIMYOU.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            BaseFont baseFont = BaseFont.createFont("D:\\test\\ttc\\msgothic.ttc,0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
//            BaseFont bfChinese = BaseFont.createFont(SIMYOU, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

            //引入特殊字符的字体
//            BaseFont baseFont = BaseFont.createFont(msgothic + ",0", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            imageFont = new Font(baseFont);
            titlefont = new Font(bfChinese, 14, Font.BOLD);
            headfont = new Font(bfChinese, 12, Font.BOLD);
            headbody = new Font(bfChinese, 12, Font.NORMAL);
            keyfont = new Font(bfChinese, 10, Font.BOLD);
            textfont = new Font(bfChinese, 10, Font.NORMAL);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void createPDF(String filename, Map<String, Object> paramMap) throws IOException {
        String content = "{\"ztbm\":\"0000000001\",\"xxxx\":{\"xxmc\":\"现象一：【X%】的【维度/标签】贡献了【Y%】的【指标】\",\"xxms\":\"全国【YYYY】年【X%】【维度/标签】贡献了【Y%】【指标】，主要集中在【省份】、【行业】，呈现了一定的聚集性。\"},\"gxxx\":{\"xxwj\":\"【XXX省】  【姓名】（【XXX】税务局）\",\"sjsh\":\"国家税务总局 【姓名】\",\"bj\":\"【XXX省】  【姓名】（【XXX】税务局）\"},\"zsxx\":{\"sjwjgc\":\"关联计算一【人/员/户/局/票】式归集的【XXXX信息】【XXXX万/亿条】，【YYYY-4】-【YYYY】年【XXXX信息】【XXXX万/亿条】\",\"zyzbbq\":\"【指标名称】、【指标名称】\"},\"xxnr\":[{\"nrbt\":\"内容1\",\"tbxx\":\"\",\"nrxx\":\"1.【YYYY】年，全国【指标】合计值为【XXX】【单位】，其中【X%】的【维度/标签】贡献了【指标】合计值为【XXX】【单位】，占全国【指标】合计值【百分比%】，【指标】贡献排名前三的省份分别为【XX省】、【XX省】和【XX省】，分别占全国总量的【百分比%】、【百分比%】和【百分比%】，（详见表X.1）。\"},{\"nrbt\":\"内容2\",\"tbxx\":\"\",\"nrxx\":\"【YYYY】年，全国【指标】行业集中情况，【指标】排名前三的行业分别为【XX行业】、【XX行业】和【XX行业】，分别占全国总量的【百分比%】、【百分比%】和【百分比%】\"}],\"fjbbdm\":[\"100302\",\"100301\",\"100304\",\"100303\"]}";

        paramMap = JsonUtils.str2Map(content);
        Document doc = new Document(PageSize.A4);
        try {
            PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(filename));
            doc.open();

            String ztbm = (String) paramMap.get("ztbm");
//            final String ztmc = GyUtils.getMcByDm("DM_SJFXBG_BGZTB", ztbm, "ZTLXMC");
//            Map<String, Object> ztMap = SjfxbgGyUtils.getZtdescCacheData(ztbm);
//            final String zttitle = (String) ztMap.get("zttitle");
//            final String ztms = (String) ztMap.get("ztdesc");
            createTitle(doc, "主题名称", ALIGN_CENTER);
            createHead(doc, "--副标题", ALIGN_CENTER);
            createHeadBody(doc, "主题描述。。。。。。。。。。", ALIGN_LEFT);


            //现象信息
            Map<String, String> xxxx = (Map<String, String>) paramMap.get("xxxx");
            //内容信息
            List<Map<String, String>> xxnr = (List<Map<String, String>>) paramMap.get("xxnr");
            //贡献信息
            Map<String, String> gxxx = (Map<String, String>) paramMap.get("gxxx");
            //注释信息
            Map<String, String> zsxx = (Map<String, String>) paramMap.get("zsxx");
            List<String> fjxx = (List<String>) paramMap.get("fjbbdm");

            createHead(doc, xxxx.get("xxmc"), ALIGN_LEFT);
            createHeadBody(doc, xxxx.get("xxms"), ALIGN_LEFT);

            for (Map<String, String> map : xxnr) {
                String nrbt = map.get("nrbt");
                String nrxx = map.get("nrxx");
                String tbxx = map.get("tbxx");
                createHead(doc, nrbt, ALIGN_LEFT);
                createHeadBody(doc, nrxx, ALIGN_LEFT);
                if (!StringUtils.isEmpty(tbxx)) {
                    String[] base64Info = tbxx.split(",");
                    String info = base64Info[0];
                    String suffix = info.substring(info.indexOf('/') + 1, info.indexOf(';'));
                    File file = convertBase64StrToImage(base64Info[1], "tbxx-pdf." + suffix);
                    createImg(doc, file.getAbsolutePath(), writer);
                    if (file.exists()) {
                        file.delete();
                    }
                }
            }

            createHead(doc, "主要贡献和个人", ALIGN_LEFT);
            createHeadBody(doc, "现象挖掘：" + gxxx.get("xxwj"), ALIGN_LEFT);
            createHeadBody(doc, "数据审核：" + gxxx.get("sjsh"), ALIGN_LEFT);
            createHeadBody(doc, "编辑：" + gxxx.get("bj"), ALIGN_LEFT);

            createHead(doc, "注释", ALIGN_LEFT);
            createKey(doc, "1.数据挖掘过程", ALIGN_LEFT);
            createHeadBody(doc, zsxx.get("sjwjgc"), ALIGN_LEFT);
            createKey(doc, "2.主要指标标签", ALIGN_LEFT);
            createHeadBody(doc, zsxx.get("zyzbbq"), ALIGN_LEFT);
            createHead(doc, "附件", ALIGN_LEFT);
            if (!CollectionUtils.isEmpty(fjxx)) {
                for (String bbdm : fjxx) {
                    createTable(doc, bbdm);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            doc.close();
        }
    }

    /**
     * @param doc      文档
     * @param filePath 图片位置
     * @param writer
     * @description 创建图片
     * @time 创建时间：2023/7/11 15:50
     * @author 作者：tianwenju
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    private static void createImg(Document doc, String filePath, PdfWriter writer) throws IOException, DocumentException {
        float restHeight = restHeight(doc, currentHeight(writer));
        Image image = null;
        try {
            image = Image.getInstance(filePath);
        } catch (Exception e) {
            System.out.println("--PDF--图片创建异常-->" + filePath);
            e.printStackTrace();
            return;
        }
        image.setAlignment(Image.ALIGN_CENTER);
        try {
            float height = image.getHeight();
            float width = image.getWidth();
            if (width > IMG_WIDTH_SIZE) {
                height = IMG_WIDTH_SIZE * height / width;
                image.scalePercent(50); //依照比例缩放
                image.scaleAbsoluteWidth(IMG_WIDTH_SIZE);
                image.scaleAbsoluteHeight(height);
            } else {
                image.scalePercent(75); //依照比例缩放
            }

            if (height > restHeight) {
                //图片高度大于剩余高度换页
                doc.newPage();
            }
        } catch (Exception e) {
            System.out.println("pdf图片缩放异常 !!");
            e.printStackTrace();
        }


        doc.add(image);
    }

    /**
     * @param doc  文档
     * @param bbdm 报表代码
     * @description 通过报表代码生成表格
     * @time 创建时间：2023/7/11 15:50
     * @author 作者：tianwenju
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    private static void createTable(Document doc, String bbdm) throws DocumentException, IOException {

        Map<String, Object> tableData = queryTableDataByBbdm(bbdm);
        List<Map<String, Object>> rows = (List<Map<String, Object>>) tableData.get("rows");
        List<Map<String, Object>> cols = (List<Map<String, Object>>) tableData.get("cols");
        if (CollectionUtils.isEmpty(rows) || CollectionUtils.isEmpty(cols)) {
            return;
        }
        //添加表頭
        createHead(doc, (String) tableData.get("title"), ALIGN_CENTER);
        PdfPTable table = generateTable(rows, cols);
        //设置table的宽度并且锁定
        table.setTotalWidth(PageSize.A4.getWidth() - 100);
        table.setLockedWidth(true);
        doc.add(table);
    }

    /**
     * @param bbdm 报表代码
     * @return 报表数据
     * @description 通过报表代码获取报表数据
     * @time 创建时间：2023/7/11 14:36
     * @author 作者：tianwenju
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    private static Map<String, Object> queryTableDataByBbdm(String bbdm) {

        // 查询数据
        //Map<String, Object> dataMap = (Map<String, Object>) SwordServiceUtils.callService("DSJYPT.QJSKJSY.HDXT.GY.QUERYCOMPONENTSC.GETRECORDLIST", new HashMap<>(), bbdm);

        List<Map<String, Object>> rowList;
//        rowList = (List<Map<String, Object>>) dataMap.get("data");

        //查询列配置信息 查询配置表头信息
        final List<Map<String, Object>> colList;
//        colList = (List<Map<String, Object>>) SwordServiceUtils.callService("DSJYPT.QJSKJSY.HDXT.GY.QUERYCOMPONENTSC.QUERYCOLBYBBDM", bbdm);

//        String title = (String) dataMap.get("title");
        String title = "title...title";
        String rows = "[{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":1233,\"qxsl\":1023,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":435,\"qxsl\":43,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"02\",\"qxzsl\":543,\"qxsl\":342,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":875,\"qxsl\":543,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":876,\"qxsl\":645,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":865,\"qxsl\":76,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":765,\"qxsl\":645,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":765,\"qxsl\":76,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":645,\"qxsl\":42,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":423,\"qxsl\":76,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":876,\"qxsl\":86,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":1233,\"qxsl\":2345,\"zbmc\":\"【2023】年全国【23.7%】的县区【纳税人数量】同比【增长】\"},{\"tjnd\":\"2022\",\"bhlb\":\"02\",\"qxzsl\":34543,\"qxsl\":5676,\"zbmc\":\"【2023】年全国【34.27%】的县区【纳税人数量】同比【减少】\"}]";
        String cols = "[{\"colend\":1,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"djxh\",\"colbegin\":1,\"rowbegin\":1,\"columncommnet\":\"序号\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"16%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4010,\"rowend\":1},{\"colend\":2,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"bhlb\",\"colbegin\":2,\"rowbegin\":1,\"columncommnet\":\"变化类别\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"16%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4011,\"rowend\":1},{\"colend\":3,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"qxsl\",\"colbegin\":3,\"rowbegin\":1,\"columncommnet\":\"区县数量\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"16%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4012,\"rowend\":1},{\"colend\":4,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"qxzsl\",\"colbegin\":4,\"rowbegin\":1,\"columncommnet\":\"区县总数量\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"16%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4013,\"rowend\":1},{\"colend\":5,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"zbmc\",\"colbegin\":5,\"rowbegin\":1,\"columncommnet\":\"指标名称\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"17%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4014,\"rowend\":1},{\"colend\":6,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"tjnd\",\"colbegin\":6,\"rowbegin\":1,\"columncommnet\":\"统计年度\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"17%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4015,\"rowend\":1}]";
        rowList = JsonUtils.str2List(rows);
        colList = JsonUtils.str2List(cols);
        System.out.println("rowList = " + JsonUtils.obj2Json(rowList));
        System.out.println("colList = " + JsonUtils.obj2Json(colList));
        Map<String, Object> res = new HashMap<>();
        res.put("title", title);
        res.put("rows", rowList);
        res.put("cols", colList);
        return res;
    }

    /**
     * @param document 文档
     * @param text     文本
     * @param align    对齐方式
     * @description title类型字体段落
     * @time 创建时间：2023/7/11 15:18
     * @author 作者：tianwenju
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    public static void createTitle(Document document, String text, int align) throws DocumentException {
        createParagraph(document, text, align, titlefont);
    }

    /**
     * @param document 文档
     * @param text     文本
     * @param align    对齐方式
     * @description head类型字体段落
     * @time 创建时间：2023/7/11 15:18
     * @author 作者：tianwenju
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    private static void createHead(Document document, String text, int align) throws DocumentException {
        createParagraph(document, text, align, headfont);
    }

    /**
     * @param document 文档
     * @param text     文本
     * @param align    对齐方式
     * @description key类型字体段落
     * @time 创建时间：2023/7/11 15:18
     * @author 作者：tianwenju
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    private static void createKey(Document document, String text, int align) throws DocumentException {
        createParagraph(document, text, align, keyfont);
    }

    /**
     * @param document 文档
     * @param text     文本
     * @param align    对齐方式
     * @description text类型字体段落
     * @time 创建时间：2023/7/11 15:18
     * @author 作者：tianwenju
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    private static void createText(Document document, String text, int align) throws DocumentException {
        createParagraph(document, text, align, textfont);
    }

    /**
     * @param document 文档
     * @param text     文本
     * @param align    对齐方式
     * @description head类型字体 段落
     * @time 创建时间：2023/7/11 15:18
     * @author 作者：tianwenju
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    public static void createHeadBody(Document document, String text, int align) throws DocumentException {
        createParagraph(document, text, align, headbody);
    }

    /**
     * @param document 文档
     * @param text     文本
     * @param align    对齐方式
     * @Font font    字体
     * @description 创建段落
     * @time 创建时间：2023/7/11 15:18
     * @author 作者：tianwenju
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    public static void createParagraph(Document document, String text, int align, Font font) throws DocumentException {
        // 段落
        Paragraph paragraph = new Paragraph(text, font);
        paragraph.setAlignment(align); //设置文字居中 0靠左   1，居中     2，靠右
        paragraph.setIndentationLeft(12); //设置左缩进
        paragraph.setIndentationRight(12); //设置右缩进
        paragraph.setFirstLineIndent(24); //设置首行缩进
        //paragraph.setLeading(50f); //行间距
        paragraph.setSpacingBefore(5f); //设置段落上空白
        paragraph.setSpacingAfter(10f); //设置段落下空白
        document.add(paragraph);
    }

    public static PdfPTable generateTable(List<Map<String, Object>> rows, List<Map<String, Object>> cols) throws DocumentException, IOException {

        String rowList = "[{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":1233,\"qxsl\":1023,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":435,\"qxsl\":43,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"02\",\"qxzsl\":543,\"qxsl\":342,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":875,\"qxsl\":543,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":876,\"qxsl\":645,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":865,\"qxsl\":76,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":765,\"qxsl\":645,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":765,\"qxsl\":76,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":645,\"qxsl\":42,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":423,\"qxsl\":76,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":876,\"qxsl\":86,\"zbmc\":\"缴费金额\"},{\"tjnd\":\"2023\",\"bhlb\":\"01\",\"qxzsl\":1233,\"qxsl\":2345,\"zbmc\":\"【2023】年全国【88.27%】的县区【纳税人数量】同比【增长】\"},{\"tjnd\":\"2022\",\"bhlb\":\"02\",\"qxzsl\":34543,\"qxsl\":5676,\"zbmc\":\"【2023】年全国【34.27%】的县区【纳税人数量】同比【减少】\"}]";
        String colList = "[{\"colend\":1,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"djxh\",\"colbegin\":1,\"rowbegin\":1,\"columncommnet\":\"序号\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"16%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4010,\"rowend\":1},{\"colend\":2,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"bhlb\",\"colbegin\":2,\"rowbegin\":1,\"columncommnet\":\"变化类别\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"16%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4011,\"rowend\":1},{\"colend\":3,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"qxsl\",\"colbegin\":3,\"rowbegin\":1,\"columncommnet\":\"区县数量\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"16%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4012,\"rowend\":1},{\"colend\":4,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"qxzsl\",\"colbegin\":4,\"rowbegin\":1,\"columncommnet\":\"区县总数量\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"16%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4013,\"rowend\":1},{\"colend\":5,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"zbmc\",\"colbegin\":5,\"rowbegin\":1,\"columncommnet\":\"指标名称\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"17%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4014,\"rowend\":1},{\"colend\":6,\"bbDm\":\"100302\",\"sort\":\"\",\"align\":\"center\",\"columnname\":\"tjnd\",\"colbegin\":6,\"rowbegin\":1,\"columncommnet\":\"统计年度\",\"autoincrement\":\"\",\"drilltype\":\"\",\"width\":\"17%\",\"drillurl\":\"\",\"fixed\":\"\",\"id\":4015,\"rowend\":1}]";
        rows = JsonUtils.str2List(rowList);
        cols = JsonUtils.str2List(colList);

        Map<Integer, String> titleMap = new HashMap<>();
        PdfPTable table = new PdfPTable(cols.size());
        for (int i = 0; i < cols.size(); i++) {
            titleMap.put(CastUtils.cast2Int(cols.get(i).get("colbegin")), CastUtils.cast2Str(cols.get(i).get("columnname")));
            table.addCell(createCell(CastUtils.cast2Str(cols.get(i).get("columncommnet")), textfont, ALIGN_CENTER, 1, 1));
        }
        for (int i = 0; i < rows.size(); i++) {
            Map<String, Object> rowMap = rows.get(i);
            for (int j = 0, col = 1; j < cols.size(); j++, col++) {
                String text = CastUtils.cast2Str(rowMap.get(titleMap.get(col)));
                table.addCell(createCell(text, textfont, ALIGN_CENTER, 1, 1));
            }
        }
        return table;
    }

    public static PdfPCell createCell(String value, Font font, int align, int colspan, int rowspan) {
        PdfPCell cell = new PdfPCell();
        cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
        cell.setHorizontalAlignment(align);
        cell.setColspan(colspan);
        cell.setRowspan(rowspan);
        cell.setFixedHeight(rowspan * 25f);
        cell.setPhrase(new Phrase(value, font));
        return cell;
    }


    /**
     * @return float
     * @description 当前高度
     * @time 创建时间：2023/8/3 10:31
     * @author 作者：tianwenju
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    private static float currentHeight(PdfWriter writer) {

        try {
            Method getPdfDocument = writer.getClass().getDeclaredMethod("getPdfDocument");
            getPdfDocument.setAccessible(true);
            PdfDocument pdf = (PdfDocument) getPdfDocument.invoke(writer);
            Field currentHeight = pdf.getClass().getDeclaredField("currentHeight");
            currentHeight.setAccessible(true);
            return (float) currentHeight.get(pdf);

        } catch (Exception e) {
            //throw new RuntimeException(e);

            return 0;
        }
    }

    /**
     * @return float
     * @description 剩余高度
     * @time 创建时间：2023/8/3 10:31
     * @author 作者：tianwenju
     * @history 修订历史（历次修订内容、修订人、修订时间等）
     */
    private static float restHeight(Document document, float usedHeight) {
        float height = document.getPageSize().getHeight() - document.bottomMargin() - document.topMargin() - usedHeight;
        System.out.println("边距 = " + document.bottomMargin() + "---top->" + document.topMargin());
        System.out.println("总高度 = " + document.getPageSize().getHeight());
        System.out.println("已使用高度 = " + usedHeight);
        System.out.println("剩余高度 = " + height);
        return height;
    }


    public static void main(String[] args) throws IOException {
        String filename = "D:\\test\\testTable3.pdf";
        Map<String, Object> param = new HashMap<>();
        createPDF(filename, param);
        System.out.println("打印完成");


    }
}
